import store from '@/store'
import { constantRoutes, asyncRoutes } from '@/router'
import { findCurrentUserTree } from '@/api/user'

const hasPermission = (roles, route) => {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => {
      if (route.meta?.roles !== undefined) {
        return route.meta.roles.includes(role)
      } else {
        return false
      }
    })
  } else {
    return true
  }
}

const filterAsyncRoutes = (routes, roles) => {
  const res = []
  routes.forEach((route) => {
    const r = { ...route }
    if (hasPermission(roles, r)) {
      if (r.children) {
        r.children = filterAsyncRoutes(r.children, roles)
      }
      res.push(r)
    }
  })
  return res
}

function filterBtnPermission(data) {
  let btnPermission = []
  data.forEach((route) => {
    let r = { ...route }
    if (r.type === 3) {
      btnPermission = [...btnPermission, r.permissionStr]
    }
    if (r.children) {
      btnPermission = [...btnPermission, ...filterBtnPermission(r.children)]
    }
  })
  return btnPermission
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(data, roles) {
  const res = []
  let btnPermission = []
  data.forEach((route) => {
    let r = { ...route }
    if (hasPermission(roles, r)) {
      if (r.children) {
        if (r.children[0].permissionStr.includes('menu:')) {
          r.children = filterAsyncRouter(r.children, roles)
        } else {
          // r.meta = {
          //   buttonPermission: r.children
          // }
          delete r.children
        }
      }
      const current = asyncRoutes.find((it) => it.permissions.includes(r.permissionStr))
      if (current) {
        r = {
          ...r,
          ...current,
          meta: {
            ...r.meta,
            ...current.meta,
            svgIcon: r.icon ? r.icon : current.meta.svgIcon,
            title: r.name
          }
        }
        res.push(r)
      }
    }
  })
  return res
}

export const usePermissionStore = defineStore('permission', () => {
  const routes = ref([])
  const dynamicRoutes = ref([])
  const btnPermission = ref([])
  const menuList = ref([])

  const setRoutes = async (roles) => {
    let accessedRoutes
    if (roles.includes('admin')) {
      accessedRoutes = asyncRoutes
    } else {
      // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // 向后端请求路由数据
      const res = await findCurrentUserTree()
      menuList.value = res.data
      console.log(res.data);

      const data = setUserMenu(res.data)
      accessedRoutes = filterAsyncRouter(data, roles)
      btnPermission.value = filterBtnPermission(res.data)
    }
    routes.value = constantRoutes.concat(accessedRoutes)
    dynamicRoutes.value = accessedRoutes
  }

  return { routes, dynamicRoutes, btnPermission, setRoutes, menuList }
})
const setUserMenu = (data) => {
  console.log(data);
  const result = data.map(item => {
    if (item.children && item.children.length) {
      const data = setUserMenu(item.children)
      return {
        ...item,
        children: data,
        permissionStr: item.permissionChar,
        type: item.type == "CATALOG" ? 1 : 2
      }
    } else {
      return {
        ...item,
        permissionStr: item.permissionChar,
        type: item.type == "CATALOG" ? 1 : 2
      }
    }

  })
  return result
}
/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
